package com.course.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.*;

import com.course.db.Student;
import com.course.db.Teacher;
import com.course.db.User;
import com.course.safe.MD5;
import com.jspsmart.upload.SmartFile;
import com.jspsmart.upload.SmartRequest;
import com.jspsmart.upload.SmartUpload;

/**
 * Servlet implementation class upload
 */
public class upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ServletConfig config;
	
	final public void init(ServletConfig config) throws ServletException {
		  this.config = config;
		 }
    /**
     * @see HttpServlet#HttpServlet()
     */
    public upload() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String type = request.getParameter("type");
		System.out.println("type:"+type);
		
		
		if(type!=null && type.equals("student"))
		{
			loadStudent(request,response);
		}
		else if(type!=null && type.equals("teacher"))
		{
			loadTeacher(request,response);
		}
	}
	
	protected void loadStudent (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
	{
		System.out.println("upload student");
		SmartUpload mySmartUpload = new SmartUpload();
		mySmartUpload.initialize(config, request, response);
		System.out.println("upload student");

		Date date = new Date();
		String studentfile= new String(), fileext=new String();
		
		try {
			mySmartUpload.upload();
			for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++)
			{
			    SmartFile myfile = mySmartUpload.getFiles().getFile(i);
			    //String fileName = new String(myfile.getFileName().getBytes("iso8859_1"),"utf-8");
			    String fileName = myfile.getFileName();
			    if(fileName != null && !fileName.equals(""))
			    {
			    	System.out.println("filename:"+fileName);
			    	studentfile = fileName.substring(0, fileName.length()-4);
				    fileext = fileName.substring(fileName.length()-4,fileName.length());
				    studentfile += date.getTime();
				    studentfile += i;
				    studentfile += fileext;

				    myfile.saveAs("files/student/"+studentfile);
				    //myfile.saveAs(studentfile);
				    System.out.println("file:"+studentfile);
					
				    System.out.println("start load file-------------------------");
					try{
						InputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/files/student/")+"/"+studentfile);
	
							jxl.Workbook rwb = Workbook.getWorkbook(is);
							for(int j=0; j<1; j++)
							{
								Sheet rs = rwb.getSheet(j); //读取第一个sheet
								int colNum=rs.getColumns();//列数
								int rowNum=rs.getRows();//行数
		
								System.out.println("colNum rowNum------------------"+rowNum+","+colNum);
								
								Student student = new Student();
								User user = new User();
								
								
								MD5 oMD5 = new MD5();
								for(int k=1; k<rowNum; k++)
								{
									Cell c = rs.getCell(0, k);
									String no = c.getContents();
									
									c = rs.getCell(1, k);
									String grade = c.getContents();
		
									c = rs.getCell(2, k);
									String name = c.getContents();
									
									c = rs.getCell(3,k);
									String strclass = c.getContents();
									
									c = rs.getCell(4,k);
									String sex = c.getContents();
		
									if(!user.userexist(no))
									{
										user.setName(no);
										user.setPassword(oMD5.getMD5ofStr(no));
										user.setType("student");
										user.add();
										
										student.setName(name);
										student.setGrade(grade);
										student.setNo(no);
										student.setStrclass(strclass);
										student.setSex(sex);
										student.setUser_id(user.lastid());
										student.add();
									}
									else
									{
										System.out.println("用户"+no+"已存在！");
									}
									
								}
							}
						}catch(Exception e)
						{
							e.printStackTrace();
						}
			    }
			}
		} catch (Exception e) {
			  e.printStackTrace();
		}
		
		//response.sendRedirect("./Admin/manage.do");
		PrintWriter out = response.getWriter();  
		out.append("<script type=\"text/javascript\">function closebox(){ this.parent.Popup.prototype.reset_m();}</script><link rel=\"stylesheet\" href=\"/css/style.css\" />导入学生数据完毕！<a href=\"javascript:closebox();\">关闭</a>");
	}
	
	protected void loadTeacher (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
	{
		System.out.println("upload student");
		SmartUpload mySmartUpload = new SmartUpload();
		mySmartUpload.initialize(config, request, response);
		System.out.println("upload student");

		Date date = new Date();
		String teacherfile= new String(), fileext=new String();
		
		try {
			mySmartUpload.upload();
			for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++)
			{
			    SmartFile myfile = mySmartUpload.getFiles().getFile(i);
			    //String fileName = new String(myfile.getFileName().getBytes("iso8859_1"),"utf-8");
			    String fileName = myfile.getFileName();
			    if(fileName != null && !fileName.equals(""))
			    {
			    	System.out.println("filename:"+fileName);
			    	teacherfile = fileName.substring(0, fileName.length()-4);
				    fileext = fileName.substring(fileName.length()-4,fileName.length());
				    teacherfile += date.getTime();
				    teacherfile += i;
				    teacherfile += fileext;

				    myfile.saveAs("files/student/"+teacherfile);
				    //myfile.saveAs(studentfile);
				    System.out.println("file:"+teacherfile);
					
				    System.out.println("start load file-------------------------");
					try{
						InputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/files/student/")+"/"+teacherfile);
	
							jxl.Workbook rwb = Workbook.getWorkbook(is);
							for(int j=0; j<1; j++)
							{
								Sheet rs = rwb.getSheet(j); //读取第一个sheet
								int colNum=rs.getColumns();//列数
								int rowNum=rs.getRows();//行数
		
								System.out.println("colNum rowNum------------------"+rowNum+","+colNum);
								
								Teacher teacher = new Teacher();
								//Student student = new Student();
								User user = new User();
								
								String team="";
								String teacher_cname="";
								String teacher_no="";
								String teacher_mobile_phone="";
								String teacher_office_phone="";
								String teacher_email="";
								String teacher_address="";
								String teacher_home_phone="";
								String teacher_contact_phone="";
								int teacher_sex=0;
								Date teacher_birthday=null;
								String teacher_nation="";
								int teacher_marrage=0;
								int teacher_politics_status=0;
								String teacher_native_place="";
								String teacher_identify="";
								String teacher_education="";
								String teacher_profession="";
								String teacher_graduate_school="";
								String teacher_position="";
								String teacher_professional_title="";
								Date teacher_work_date=null;
								Date teacher_attend_date=null;
								String teacher_skill_level="";
								Date teacher_skill_level_date=null;
								String teacher_department="";
								
								
								//int teacher_status;
								//String teacher_photo_src;
								//Date teacher_create_date;
								//Date teacher_modified_date;
								SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");

								
								MD5 oMD5 = new MD5();
								for(int k=4; k<rowNum; k++)
								{
									Cell c = rs.getCell(0, k);
									team = c.getContents();
									
									c = rs.getCell(1, k);
									teacher_cname = c.getContents();
		
									c = rs.getCell(2, k);
									teacher_no = c.getContents();
									
									c = rs.getCell(3, k);
									teacher_mobile_phone = c.getContents();
									
									c = rs.getCell(4, k);
									teacher_office_phone = c.getContents();
									
									c = rs.getCell(5, k);
									teacher_email = c.getContents();
									
									c = rs.getCell(6, k);
									teacher_address = c.getContents();
									
									c = rs.getCell(7, k);
									teacher_home_phone = c.getContents();
									
									c = rs.getCell(8, k);
									teacher_contact_phone = c.getContents();
									
									c = rs.getCell(9, k);
									if(c.getContents().trim().equals("男"))
										teacher_sex = 0;
									else if(c.getContents().trim().equals("女"))
										teacher_sex = 1;
									
									c = rs.getCell(10, k);
									if(c.getContents()!=null && !c.getContents().equals("无"))
									try {
										teacher_birthday = formatDate.parse(c.getContents());
									} catch (ParseException e) {
										e.printStackTrace();
									}

									
									c = rs.getCell(11, k);
									teacher_nation = c.getContents();
									
									c = rs.getCell(12, k);
									if(c.getContents()!=null&&c.getContents().equals("已婚"))
										teacher_marrage = 1;
									else if(c.getContents()!=null&&c.getContents().equals("未婚"))
										teacher_marrage = 0;
									
									c = rs.getCell(13, k);
									if(c.getContents()!=null)
										teacher_politics_status = Integer.parseInt(c.getContents());
									
									c = rs.getCell(14, k);
									teacher_native_place = c.getContents();
									
									c = rs.getCell(15, k);
									teacher_identify = c.getContents();
									
									c = rs.getCell(16, k);
									teacher_education = c.getContents();
									
									c = rs.getCell(17, k);
									teacher_profession = c.getContents();
									
									c = rs.getCell(18, k);
									teacher_graduate_school = c.getContents();
									
									c = rs.getCell(19, k);
									teacher_position = c.getContents();
									
									c = rs.getCell(20, k);
									teacher_professional_title = c.getContents();
									
									c = rs.getCell(21, k);
									if(c.getContents()!=null && !c.getContents().equals("无"))
										try {
											teacher_work_date = formatDate.parse(c.getContents());
										} catch (ParseException e) {
											e.printStackTrace();
										}
									
									c = rs.getCell(22, k);
									if(c.getContents()!=null && !c.getContents().equals("无"))
										try {
											teacher_attend_date = formatDate.parse(c.getContents());
										} catch (ParseException e) {
											e.printStackTrace();
										}
									
									c = rs.getCell(23, k);
									teacher_skill_level = c.getContents();
									
									c = rs.getCell(24, k);
									if(c.getContents()!=null && !c.getContents().equals("无"))
										try {
											teacher_skill_level_date = formatDate.parse(c.getContents());
										} catch (ParseException e) {
											e.printStackTrace();
										}
									
									c = rs.getCell(25, k);
									teacher_department = c.getContents();
		
									if(!user.userexist(teacher_no))
									{
										user.setName(teacher_no);
										user.setPassword(oMD5.getMD5ofStr(teacher_no));
										user.setType("teacher");
										user.add();
										
										
										teacher.setTeam(team);
										teacher.setName(teacher_cname);
										teacher.setTeacher_no(teacher_no);
										teacher.setTeacher_mobile_phone(teacher_mobile_phone);
										teacher.setTeacher_office_phone(teacher_office_phone);
										teacher.setTeacher_email(teacher_email);
										teacher.setTeacher_address(teacher_address);
										teacher.setTeacher_home_phone(teacher_home_phone);
										teacher.setTeacher_contact_phone(teacher_contact_phone);
										teacher.setTeacher_sex(teacher_sex);
										teacher.setTeacher_birthday(teacher_birthday);
										teacher.setTeacher_nation(teacher_nation);
										teacher.setTeacher_marrage(teacher_marrage);
										teacher.setTeacher_politics_status(teacher_politics_status);
										teacher.setTeacher_native_place(teacher_native_place);
										teacher.setTeacher_identify(teacher_identify);
										teacher.setTeacher_education(teacher_education);
										teacher.setTeacher_profession(teacher_profession);
										
										teacher.setTeacher_graduate_school(teacher_graduate_school);
										teacher.setTeacher_position(teacher_position);
										teacher.setTeacher_professional_title(teacher_professional_title);
										teacher.setTeacher_work_date(teacher_work_date);
										teacher.setTeacher_attend_date(teacher_attend_date);
										teacher.setTeacher_skill_level(teacher_skill_level);
										teacher.setTeacher_skill_level_date(teacher_skill_level_date);
										teacher.setTeacher_department(teacher_department);
										
										
										teacher.setUser_id(user.lastid());
										teacher.add();
									}
									else
									{
										System.out.println("用户"+teacher_no+"已存在！");
									}
									
								}
							}
						}catch(Exception e)
						{
							e.printStackTrace();
						}
			    }
			}
		} catch (Exception e) {
			  e.printStackTrace();
		}
		
		//response.sendRedirect("./Admin/manage.do");
		PrintWriter out = response.getWriter();  
		out.append("<script type=\"text/javascript\">function closebox(){ this.parent.Popup.prototype.reset_m();}</script><link rel=\"stylesheet\" href=\"/css/style.css\" />导入教师数据完毕！<a href=\"javascript:closebox();\">关闭</a>");
	}

}
